/***
 * @description order rouer
 * @author zhang
 */

const Order = require('../models/Order')
const Address = require('../models/Address')
const Product = require('../models/Product')
// const { context } = require('../app')

/**
 * 创建订单数据库
 * @param {Object} data 订单信息
 * @param {String} username 用户
 * @returns 
 */
const OrderDb = async (data, username) => {
    // 获取收货地址
    const address = await Address.findById(data.addressId)

    // 获取前端发来的id 然后转换成数组
    console.log(data)
    const productIdList = data.products.map(item => {
        return item.id
    })

    //查询数据库的商品
    const productList = await Product.find({
        shopId: data.shopId,
        _id: {
            $in: productIdList
        }
    })

    // 拼接数据 
    const productData = productList.map(item => {
        // 获取商品id
        const id = item._id.toString()
        // 筛选前端商品数量
        const countsList = data.products.filter(item => {
            return item.id == id
        })
        if(countsList.length === 0) {
            throw Error('未找到匹配的销售数据')
        }

        return {
            product: item,
            orderSalese: countsList[0].num
        }
    })

    const orderDate = await Order.create({
        username,
        shopId:data.shopId,
        shopName: data.shopName,
        isCanceled: data.isCanceled,
        products: productData,
        address
    })

    return orderDate
}


// 获取订单数据库
const orderList = async () => {
    const order = await Order.find()

    return order
}

module.exports = {
    OrderDb,
    orderList
}